import redis
from tornado.options import options

from libs.tools.widget import Common
from libs.enums.redis_keys import RedisConfs


class RedisObject(object):

    def __init__(self, redis_key):
        self.pool = options.config['redis_pools'][redis_key]
        self.conn = redis.Redis(connection_pool=self.pool)

    def _get_redis_key(self, key, key_format):
        conf = RedisConfs[key]
        rk = conf["key"].format(**key_format) if key_format else conf["key"]
        return rk

    def get(self, key, key_format=None, data_type=None):
        """
        :key -> str, 必须是RedisConfs中记录的key
        :key_format -> dict, 需要替换key中相关信息
        :data_type -> 默认为None
            :json -> 先进行json转义再输出
        """
        conf = RedisConfs[key]
        if conf.get("need_format") and not key_format:
            assert False
        rk = self._get_redis_key(key, key_format)
        data = self.conn.get(rk)
        if data_type == "json" and data:
            data = Common.json_loads(data)
        return Common.utf8(data)

    def set(self, key, data, key_format=None, ex=None, data_type=None):
        """
        :key -> str, 必须是RedisConfs中记录的key
        :data -> 需要缓存的数据
        :key_format -> dict, 需要替换key中相关信息
        :ex -> 过期时间, 如果ex为空, 默认使用RedisConfs中ex, 建议使用RedisConfs中ex
        :data_type -> 默认为None
            :json -> 先转为json再缓存
        """
        conf = RedisConfs[key]
        if conf.get("need_format") and not key_format:
            assert False
        rk = self._get_redis_key(key, key_format)
        ex = conf.get("ex", 0) if ex is None else ex
        if data_type == "json":
            data = Common.json_dumps(data)
        if ex > 0:
            self.conn.set(rk, data, ex)
        else:
            self.conn.set(rk, data)
